/**
 * Copyright 2019 覃海林(qinhaisenlin@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wangzha.portal.core.ctrl;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wangzha.common.base.BaseController;
import com.wangzha.common.kit.RSAKit;
import com.wangzha.common.model.SysOrg;
import com.wangzha.common.model.SysUser;
import com.wangzha.common.safe.TokenValidator;
import com.wangzha.common.visit.Visitor;
import com.wangzha.common.vo.Feedback;
import com.wangzha.portal.core.service.SysOrgService;
import com.wangzha.portal.core.service.SysUserRoleService;
import com.wangzha.portal.core.service.SysUserService;
import org.apache.commons.lang3.math.NumberUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * 用户
 *
 */
@Path("/portal/core/sysUser")
public class SysUserController extends BaseController {
    @Inject
    SysUserService service;
    @Inject
    SysOrgService sysOrgService;
    @Inject
    SysUserRoleService sysUserRoleService;

    public void index() {
        setAttr("orgList", service.queryOrgIdAndNameRecord());
        render("index.html");
    }


    public void list() {
        Record record = new Record();
        record.set("userCode", getPara("userCode"));
        record.set("userName", getPara("userName"));
        record.set("orgId", getPara("orgId"));
        record.set("sex", getPara("sex"));
        record.set("type", getPara("type", "user"));
        //if (StringUtils.isNotBlank(getVisitor().getCode()) && !"superadmin".equals(getVisitor().getCode())) {
        record.set("visitorCode", getVisitor().getCode());
        //}
        renderJson(service.page(getParaToInt("pageNumber", 1), getParaToInt("pageSize", 10), record));
    }

    public void add() {
        setAttr("orgList", service.queryOrgIdAndNameRecord());
        render("add.html");
    }

    public void save() {
        SysUser sysUser = getBean(SysUser.class);
        sysUser.setId(sysUser.getUserCode());
        sysUser.setSuperCode(getVisitor().getCode());
        sysUser.setPortCountRecord(sysUser.getPort() + NumberUtils.toInt(sysUser.getPortCountRecord() + ""));
        SysUser user = service.findByUserCode(getVisitor().getCode());
        if (user.getPort() != null && sysUser.getPort() != null)
            if (user.getPort() >= sysUser.getPort() && user.getPort() > 0) {
                if (sysUser.getPasswd() == null) {
                    setAttr("sysUser", getBean(SysUser.class));
                    sysUser.setPasswd(sysUser.getUserCode() + "123");
                } else {
                    setAttr("sysUser", sysUser);
                }
                if (!this.service.saveEntity(sysUser)) {
                    setException("用户编号已存在,请重新输入");
                } else {
                    user.setPort(Integer.valueOf(user.getPort().intValue() - sysUser.getPort().intValue()));
                    user.update();
                }
            } else {
                setException("你的设备数量不足,不能给下级分配");
            }
        setAttr("orgList", this.service.queryOrgIdAndNameRecord());
        render("add.html");
    }

    public void edit() throws UnsupportedEncodingException {
        SysUser entity = (SysUser) service.findById(URLDecoder.decode(getPara(), "utf-8"));
        entity.setUserName(entity.getUserName().trim());
        entity.setPasswd("******");
        setAttr("sysUser", entity);
        setAttr("orgList", service.queryOrgIdAndNameRecord());
        render("edit.html");
    }

    public void update() {
        SysUser sysUserBean = (SysUser)getBean(SysUser.class);
        if (sysUserBean.getOrgId() == null)
            sysUserBean.setOrgId("sys");
        SysUser user = this.service.findByUserCode(sysUserBean.getUserCode());
        sysUserBean.setPortCountRecord(Integer.valueOf(user.getPortCountRecord().intValue() + sysUserBean.getPort().intValue() - user.getPort().intValue()));
        sysUserBean.update();
        sysUserBean.setPasswd("******");
        setAttr("sysUser", sysUserBean);
        setAttr("orgList", this.service.queryOrgIdAndNameRecord());
        render("edit.html");
    }

    public void delete() {
        List<SysUser> sysUserList = (List<SysUser>) service.findByIds(getIds());
        int sumPort = 0;
        for (SysUser sysUser : sysUserList) {
            sumPort += sysUser.getPort();
            // 删除后要把端口返回给上级代理
            service.updatePortByUserCode(sysUser.getSuperCode(), sumPort);
            service.deleteById(sysUser.getId());
        }
        renderJson(Feedback.success());
    }

    public void isAllowLogin() {
        SysUser entity = (SysUser) service.findById(getPara("id"));
        entity.setAllowLogin(getParaToInt("state"));
        service.update(entity);
        renderJson(suc());
    }

    /**
     * 重置密码
     *
     * @author QinHaiLin
     * @date 2018年12月5日
     */
    public void resetPassword() {
        service.resetPassword(getIds());
        renderJson(suc());
    }

    public void my() {
        createToken();
        SysUser entity = service.findByUserCode(getVisitor().getCode());
        setAttr("sysUser", entity);
        SysOrg org = (SysOrg) sysOrgService.findById(entity.getOrgId());
        setAttr("orgName", org.getOrgName());
        render("my/index.html");
    }

    /**
     * 修改个人信息
     */
    @Before(TokenValidator.class)
    public void updateMy() {
        SysUser sysUser = getBean(SysUser.class);
        Visitor vs = getVisitor();
        if (!vs.getCode().equals(sysUser.getUserCode())) {
            getResponse().setStatus(403);
            renderError(403);
        }
        sysUser.update();
        setAttr("sysUser", sysUser);
        SysOrg org = (SysOrg) sysOrgService.findById(sysUser.getOrgId());
        setAttr("orgName", org.getOrgName());
        setAttr("msg", "数据修改成功");
        render("my/index.html");
    }

    public void myPassword() {
        createToken();
        setAttr("userCode", getVisitor().getCode());
        render("my/password.html");
    }

    /**
     * 修改个人密码
     */
    @Before(TokenValidator.class)
    public void updateMypassword() {
        Visitor vs = getVisitor();
        if (!vs.getCode().equals(getPara("userCode"))) {
            getResponse().setStatus(403);
            renderError(403);
        }
        String oldPassword = getPara("oldPassword");
        String newPassword = getPara("newPassword");
        try {
            oldPassword = RSAKit.decryptionToString(oldPassword);
            newPassword = RSAKit.decryptionToString(newPassword);
        } catch (Exception e) {
            handerException(e);
        }
        boolean b = service.updatePassword(vs.getCode(), newPassword, oldPassword);
        if (b) {
            setAttr("msg", "密码修改成功");
        } else {
            createToken();
            setException("原密码错误,密码修改失败");
        }

        setAttr("userCode", vs.getCode());
        render("my/password.html");
    }

    /**
     * 用户角色
     */
    public void userRole() {
        setAttr("userCode", getPara("userCode"));
        setAttr("userName", getPara("userName"));
        render("userRole.html");
    }

    public void saveUserRole() {
        //用户原有的角色(登录者却没有)
        StringBuffer sbf = new StringBuffer();
        if (!getVisitor().getCode().equals("superadmin")) {//超级管理员登录不查询
            List<Record> userRoleList = sysUserRoleService.queryUserRoleList(getPara("userCode"), getVisitor().getCode());
            for (Record rd : userRoleList) {
                sbf.append(rd.getStr("role_code")).append(",");
            }
        }
        //可配置的角色
        sbf.append(getPara("role"));

        String[] roles = sbf.toString().split(",");
        String userCode = getPara("userCode");
        boolean b = sysUserRoleService.saveUserRole(userCode, roles);
        if (!b) {
            renderJson(err("保存失败"));
            return;
        }
        renderJson(suc("保存成功"));
    }

    /**
     * 查询用户角色
     */
    public void queryUserRole() {
        renderJson(sysUserRoleService.queryUserRoleList(getPara("userCode")));
    }


    public void recharge() {
        SysUser sysUser = service.findByUserCode(getPara("userCode"));
        setAttr("sysUser", sysUser);
        render("recharge.html");
    }

    public void saveRecharge() {
        int port = getInt("port");
        if (port <=0) {
            SysUser sysUser = service.findByUserCode(getPara("userCode"));
            setAttr("sysUser", sysUser);
            setException("端口号数量不能为负数");
        } else {
            SysUser visitorUser = service.findByUserCode(getVisitor().getCode());
            if (visitorUser.getPort() < port) {
                setException("你的设备数量不足，不能给下级分配");
            } else {
                Db.tx(() -> service.updatePortByUserCode(getPara("userCode"), port) &&
                        service.updatePortByUserCode(getVisitor().getCode(), -port));
            }
        }

        render("recharge.html");
    }
}
